import { prisma } from '../db/prisma';
import { createSuccessResponse, createErrorResponse } from '../utils/response';
import { CompletionCycle } from '@prisma/client';

export class ReminderService {
  /**
   * 保存用户提醒设置
   */
  static async saveReminderSettings(input: {
    managerId: number;
    weeklyReminder: boolean;
    deadlineReminder: boolean;
    reminderTime: string;
  }) {
    try {
      const settings = await prisma.reminderSettings.upsert({
        where: { managerId: input.managerId },
        update: {
          weeklyReminder: input.weeklyReminder,
          deadlineReminder: input.deadlineReminder,
          reminderTime: input.reminderTime,
        },
        create: {
          managerId: input.managerId,
          weeklyReminder: input.weeklyReminder,
          deadlineReminder: input.deadlineReminder,
          reminderTime: input.reminderTime,
        },
      });

      return createSuccessResponse(settings, '提醒设置保存成功');
    } catch (error) {
      console.error('保存提醒设置失败:', error);
      return createErrorResponse('保存提醒设置失败');
    }
  }

  /**
   * 获取用户提醒设置
   */
  static async getReminderSettings(input: { managerId: number }) {
    try {
      let settings = await prisma.reminderSettings.findUnique({
        where: { managerId: input.managerId },
      });

      // 如果没有设置记录，创建默认设置
      if (!settings) {
        settings = await prisma.reminderSettings.create({
          data: {
            managerId: input.managerId,
            weeklyReminder: true,
            deadlineReminder: true,
            reminderTime: '09:00',
          },
        });
      }

      return createSuccessResponse(settings, '获取提醒设置成功');
    } catch (error) {
      console.error('获取提醒设置失败:', error);
      return createErrorResponse('获取提醒设置失败');
    }
  }

  /**
   * 获取客户经理的完整任务数据（合并多个接口，减少数据库查询）
   */
  static async getTaskDashboard(input: { 
    managerId: number;
    includeProgressComparison?: boolean;
  }) {
    try {
      const now = new Date();
      const currentMonth = now.getMonth() + 1;
      const currentYear = now.getFullYear();
      const currentQuarter = Math.ceil(currentMonth / 3);

      // 一次性获取客户经理负责的所有服务和相关数据
      const managerServices = await prisma.service.findMany({
        include: {
          clientAssignments: {
            include: {
              client: {
                include: {
                  managerAssignments: {
                    where: { managerId: input.managerId },
                  },
                },
              },
            },
          },
        },
      });

      const taskSummary = [];
      const reminders = [];

      for (const service of managerServices) {
        // 筛选出该客户经理负责的客户
        const relevantClients = service.clientAssignments
          .filter(assignment => assignment.client.managerAssignments.length > 0)
          .map(assignment => assignment.client);

        if (relevantClients.length === 0) continue;

        let startDate: Date;
        let endDate: Date;

        // 根据服务周期计算时间范围
        switch (service.completionCycle) {
          case CompletionCycle.monthly:
            startDate = new Date(currentYear, currentMonth - 1, 1);
            endDate = new Date(currentYear, currentMonth, 0);
            break;
          case CompletionCycle.quarterly:
            const quarterStartMonth = (currentQuarter - 1) * 3;
            startDate = new Date(currentYear, quarterStartMonth, 1);
            endDate = new Date(currentYear, quarterStartMonth + 3, 0);
            break;
          case CompletionCycle.yearly:
            startDate = new Date(currentYear, 0, 1);
            endDate = new Date(currentYear, 11, 31);
            break;
          default:
            continue;
        }

        // 获取该时间段内的完成记录
        const completedLogs = await prisma.workLog.findMany({
          where: {
            managerId: input.managerId,
            serviceId: service.id,
            completionDate: {
              gte: startDate,
              lte: endDate,
            },
          },
        });

        const completedClientIds = new Set(completedLogs.map(log => log.clientId));
        const totalClients = relevantClients.length;
        const completedCount = completedClientIds.size;
        const uncompletedCount = totalClients - completedCount;
        // 特殊处理四员协同服务项目：完成1家客户即为100%进度
        let progressPercentage = 0;
        if (service.serviceName && service.serviceName.includes('四员协同')) {
          progressPercentage = completedCount > 0 ? 100 : 0;
        } else {
          progressPercentage = totalClients > 0 ? Math.round((completedCount / totalClients) * 100) : 0;
        }

        // 计算截止日期
        let deadline: Date;
        if (service.endDate) {
          deadline = new Date(service.endDate);
        } else {
          deadline = endDate;
        }

        const daysUntilDeadline = Math.ceil((deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));

        // 构建任务汇总数据
        const taskData = {
          serviceId: service.id,
          serviceName: service.serviceName,
          completionCycle: service.completionCycle,
          totalClients,
          completedCount,
          uncompletedCount,
          progressPercentage,
          deadline,
          daysRemaining: daysUntilDeadline,
          period: {
            startDate,
            endDate,
            cycle: service.completionCycle,
          },
        };

        // 添加智能评估数据（可选，减少默认查询）
        if (input.includeProgressComparison && totalClients > 0) {
          try {
            const comparison = await this.getProgressComparison({
              managerId: input.managerId,
              serviceId: service.id,
            });
            if (comparison.success) {
              taskData.assessment = comparison.data.assessment;
              taskData.peerComparison = comparison.data.peerComparison;
              taskData.historicalComparison = comparison.data.historicalComparison;
            }
          } catch (error) {
            console.warn(`获取服务 ${service.id} 的进度比较失败:`, error);
          }
        }

        taskSummary.push(taskData);

        // 检查是否需要提醒
        const userSettings = await this.getReminderSettingsSync(input.managerId);
        const shouldRemind = uncompletedCount > 0 && (
          (userSettings.weeklyReminder && now.getDay() === 1) ||
          (userSettings.deadlineReminder && daysUntilDeadline <= 3)
        );

        if (shouldRemind) {
          let reminderType = '';
          if (now.getDay() === 1) reminderType = 'weekly';
          if (daysUntilDeadline <= 3) {
            reminderType = daysUntilDeadline <= 0 ? 'overdue' : 'deadline';
          }

          let reminderMessage = '';
          switch (service.completionCycle) {
            case CompletionCycle.monthly:
              reminderMessage = `本月您还有${uncompletedCount}户客户的"${service.serviceName}"未完成！`;
              break;
            case CompletionCycle.quarterly:
              reminderMessage = `本季度"${service.serviceName}"工作进度落后，您还有${uncompletedCount}户未完成！`;
              break;
            case CompletionCycle.yearly:
              reminderMessage = `本年度"${service.serviceName}"工作进度落后，您还有${uncompletedCount}户未完成！`;
              break;
          }

          reminders.push({
            serviceId: service.id,
            serviceName: service.serviceName,
            completionCycle: service.completionCycle,
            totalClients,
            completedCount,
            uncompletedCount,
            deadline,
            daysUntilDeadline,
            reminderType,
            reminderMessage,
            customReminderContent: service.reminderContent,
          });
        }
      }

      return createSuccessResponse({
        taskSummary,
        reminders,
        timestamp: now.toISOString(),
      }, '获取任务数据成功');

    } catch (error) {
      console.error('获取任务数据失败:', error);
      return createErrorResponse('获取任务数据失败');
    }
  }

  /**
   * 获取用户提醒设置（同步版本，避免重复查询）
   */
  private static async getReminderSettingsSync(managerId: number) {
    let settings = await prisma.reminderSettings.findUnique({
      where: { managerId },
    });

    if (!settings) {
      settings = await prisma.reminderSettings.create({
        data: {
          managerId,
          weeklyReminder: true,
          deadlineReminder: true,
          reminderTime: '09:00',
        },
      });
    }

    return settings;
  }

  /**
   * 获取客户经理的任务提醒（保留原接口，向后兼容）
   */
  static async getReminders(input: { managerId: number }) {
    try {
      const now = new Date();
      const currentMonth = now.getMonth() + 1;
      const currentYear = now.getFullYear();
      const currentQuarter = Math.ceil(currentMonth / 3);

      // 获取客户经理负责的所有服务
      const managerServices = await prisma.service.findMany({
        include: {
          clientAssignments: {
            include: {
              client: {
                include: {
                  managerAssignments: {
                    where: { managerId: input.managerId },
                  },
                },
              },
            },
          },
        },
      });

      const reminders = [];

      for (const service of managerServices) {
        // 筛选出该客户经理负责的客户
        const relevantClients = service.clientAssignments
          .filter(assignment => assignment.client.managerAssignments.length > 0)
          .map(assignment => assignment.client);

        if (relevantClients.length === 0) continue;

        let startDate: Date;
        let endDate: Date;

        // 根据服务周期计算时间范围
        switch (service.completionCycle) {
          case CompletionCycle.monthly:
            startDate = new Date(currentYear, currentMonth - 1, 1);
            endDate = new Date(currentYear, currentMonth, 0);
            break;
          case CompletionCycle.quarterly:
            const quarterStartMonth = (currentQuarter - 1) * 3;
            startDate = new Date(currentYear, quarterStartMonth, 1);
            endDate = new Date(currentYear, quarterStartMonth + 3, 0);
            break;
          case CompletionCycle.yearly:
            startDate = new Date(currentYear, 0, 1);
            endDate = new Date(currentYear, 11, 31);
            break;
          default:
            continue;
        }

        // 获取该时间段内的完成记录
        const completedLogs = await prisma.workLog.findMany({
          where: {
            managerId: input.managerId,
            serviceId: service.id,
            completionDate: {
              gte: startDate,
              lte: endDate,
            },
          },
        });

        const completedClientIds = new Set(completedLogs.map(log => log.clientId));
        const totalClients = relevantClients.length;
        const completedCount = completedClientIds.size;
        const uncompletedCount = totalClients - completedCount;

        // 计算截止日期
        let deadline: Date;
        if (service.endDate) {
          deadline = new Date(service.endDate);
        } else {
          deadline = endDate;
        }

        // 计算距离截止日期的天数
        const daysUntilDeadline = Math.ceil((deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));

        // 获取用户提醒设置
        const userSettings = await prisma.reminderSettings.findUnique({
          where: { managerId: input.managerId },
        });

        // 如果没有设置，使用默认设置
        const weeklyReminderEnabled = userSettings?.weeklyReminder ?? true;
        const deadlineReminderEnabled = userSettings?.deadlineReminder ?? true;

        // 判断是否需要提醒（基于用户设置）
        const shouldRemind = uncompletedCount > 0 && (
          (weeklyReminderEnabled && now.getDay() === 1) || // 周一提醒（用户启用时）
          (deadlineReminderEnabled && daysUntilDeadline <= 3) // 截止前3天提醒（用户启用时）
        );

        if (shouldRemind) {
          let reminderType = '';
          let reminderMessage = '';

          if (now.getDay() === 1) {
            reminderType = 'weekly';
          }
          if (daysUntilDeadline <= 3) {
            reminderType = daysUntilDeadline <= 0 ? 'overdue' : 'deadline';
          }

          // 生成提醒消息
          switch (service.completionCycle) {
            case CompletionCycle.monthly:
              reminderMessage = `本月您还有${uncompletedCount}户客户的"${service.serviceName}"未完成！`;
              break;
            case CompletionCycle.quarterly:
              reminderMessage = `本季度"${service.serviceName}"工作进度落后，您还有${uncompletedCount}户未完成！`;
              break;
            case CompletionCycle.yearly:
              reminderMessage = `本年度"${service.serviceName}"工作进度落后，您还有${uncompletedCount}户未完成！`;
              break;
          }

          reminders.push({
            serviceId: service.id,
            serviceName: service.serviceName,
            completionCycle: service.completionCycle,
            totalClients,
            completedCount,
            uncompletedCount,
            deadline,
            daysUntilDeadline,
            reminderType,
            reminderMessage,
            customReminderContent: service.reminderContent,
          });
        }
      }

      return createSuccessResponse(reminders, '获取任务提醒成功');
    } catch (error) {
      console.error('获取任务提醒失败:', error);
      return createErrorResponse('获取任务提醒失败');
    }
  }

  /**
   * 获取服务项目的详细进度
   */
  static async getServiceProgress(input: {
    managerId: number;
    serviceId: number;
  }) {
    try {
      const service = await prisma.service.findUnique({
        where: { id: input.serviceId },
      });

      if (!service) {
        return createErrorResponse('服务项目不存在');
      }

      const now = new Date();
      const currentMonth = now.getMonth() + 1;
      const currentYear = now.getFullYear();
      const currentQuarter = Math.ceil(currentMonth / 3);

      let startDate: Date;
      let endDate: Date;

      // 根据服务周期计算时间范围
      switch (service.completionCycle) {
        case CompletionCycle.monthly:
          startDate = new Date(currentYear, currentMonth - 1, 1);
          endDate = new Date(currentYear, currentMonth, 0);
          break;
        case CompletionCycle.quarterly:
          const quarterStartMonth = (currentQuarter - 1) * 3;
          startDate = new Date(currentYear, quarterStartMonth, 1);
          endDate = new Date(currentYear, quarterStartMonth + 3, 0);
          break;
        case CompletionCycle.yearly:
          startDate = new Date(currentYear, 0, 1);
          endDate = new Date(currentYear, 11, 31);
          break;
        default:
          return createErrorResponse('不支持的完成周期');
      }

      // 获取客户经理负责的需要此服务的客户
      const managerClients = await prisma.managerClientAssignment.findMany({
        where: { managerId: input.managerId },
        include: {
          client: {
            include: {
              serviceAssignments: {
                where: { serviceId: input.serviceId },
              },
            },
          },
        },
      });

      const clientsWithService = managerClients
        .filter(assignment => assignment.client.serviceAssignments.length > 0)
        .map(assignment => assignment.client);

      // 获取完成记录
      const completedLogs = await prisma.workLog.findMany({
        where: {
          managerId: input.managerId,
          serviceId: input.serviceId,
          completionDate: {
            gte: startDate,
            lte: endDate,
          },
        },
        include: {
          client: true,
        },
        orderBy: {
          completionDate: 'desc',
        },
      });

      const completedClientIds = new Set(completedLogs.map(log => log.clientId));
      const completedClients = clientsWithService.filter(client => 
        completedClientIds.has(client.id)
      );
      const uncompletedClients = clientsWithService.filter(client => 
        !completedClientIds.has(client.id)
      );

      return createSuccessResponse({
        service,
        period: {
          startDate,
          endDate,
          cycle: service.completionCycle,
        },
        totalClients: clientsWithService.length,
        completedCount: completedClients.length,
        uncompletedCount: uncompletedClients.length,
        completedClients,
        uncompletedClients,
        recentLogs: completedLogs.slice(0, 10),
        progressPercentage: clientsWithService.length > 0 
          ? Math.round((completedClients.length / clientsWithService.length) * 100)
          : 0,
      }, '获取服务进度成功');
    } catch (error) {
      console.error('获取服务进度失败:', error);
      return createErrorResponse('获取服务进度失败');
    }
  }

  /**
   * 获取进度的横向和纵向对比数据
   */
  static async getProgressComparison(input: {
    managerId: number;
    serviceId: number;
  }) {
    try {
      const service = await prisma.service.findUnique({
        where: { id: input.serviceId },
      });

      if (!service) {
        return createErrorResponse('服务项目不存在');
      }

      const now = new Date();
      const currentMonth = now.getMonth() + 1;
      const currentYear = now.getFullYear();
      const currentQuarter = Math.ceil(currentMonth / 3);

      let startDate: Date;
      let endDate: Date;

      // 根据服务周期计算当前期间的时间范围
      switch (service.completionCycle) {
        case CompletionCycle.monthly:
          startDate = new Date(currentYear, currentMonth - 1, 1);
          endDate = new Date(currentYear, currentMonth, 0);
          break;
        case CompletionCycle.quarterly:
          const quarterStartMonth = (currentQuarter - 1) * 3;
          startDate = new Date(currentYear, quarterStartMonth, 1);
          endDate = new Date(currentYear, quarterStartMonth + 3, 0);
          break;
        case CompletionCycle.yearly:
          startDate = new Date(currentYear, 0, 1);
          endDate = new Date(currentYear, 11, 31);
          break;
        default:
          return createErrorResponse('不支持的完成周期');
      }

      // 1. 计算当前客户经理的进度
      const currentProgress = await this.calculateManagerProgress(input.managerId, input.serviceId, startDate, endDate);

      // 2. 横向对比：获取所有客户经理在当前期间的进度
      const allManagers = await prisma.manager.findMany({});

      const peerProgressPromises = allManagers.map(async (manager) => {
        if (manager.id === input.managerId) return null; // 排除自己
        return await this.calculateManagerProgress(manager.id, input.serviceId, startDate, endDate);
      });

      const peerProgressResults = await Promise.all(peerProgressPromises);
      const peerProgresses = peerProgressResults.filter(p => p !== null && p.totalClients > 0);

      // 3. 纵向对比：获取该客户经理过去几个周期的进度
      const historicalProgresses = await this.getHistoricalProgress(input.managerId, input.serviceId, service.completionCycle);

      // 4. 计算横向对比数据
      const peerRates = peerProgresses.map(p => p!.progressRate);
      const peerComparison = this.calculatePeerComparison(currentProgress.progressRate, peerRates);

      // 5. 计算纵向对比数据
      const historicalComparison = this.calculateHistoricalComparison(currentProgress.progressRate, historicalProgresses);

      // 6. 综合评估
      const assessment = this.calculateProgressAssessment({
        currentProgress,
        peerComparison,
        historicalComparison,
        timeProgress: this.calculateTimeProgress(startDate, endDate),
      });

      return createSuccessResponse({
        currentProgress,
        peerComparison,
        historicalComparison,
        assessment,
        period: { startDate, endDate, cycle: service.completionCycle },
      }, '获取进度对比数据成功');

    } catch (error) {
      console.error('获取进度对比失败:', error);
      return createErrorResponse('获取进度对比失败');
    }
  }

  /**
   * 计算单个客户经理的进度
   */
  private static async calculateManagerProgress(managerId: number, serviceId: number, startDate: Date, endDate: Date) {
    // 获取客户经理负责的需要此服务的客户
    const managerClients = await prisma.managerClientAssignment.findMany({
      where: { managerId },
      include: {
        client: {
          include: {
            serviceAssignments: {
              where: { serviceId },
            },
          },
        },
      },
    });

    const clientsWithService = managerClients
      .filter(assignment => assignment.client.serviceAssignments.length > 0)
      .map(assignment => assignment.client);

    // 获取完成记录
    const completedLogs = await prisma.workLog.findMany({
      where: {
        managerId,
        serviceId,
        completionDate: {
          gte: startDate,
          lte: endDate,
        },
      },
    });

    const completedCount = new Set(completedLogs.map(log => log.clientId)).size;
    const totalClients = clientsWithService.length;
    const progressRate = totalClients > 0 ? (completedCount / totalClients) * 100 : 0;

    return {
      managerId,
      totalClients,
      completedCount,
      progressRate,
    };
  }

  /**
   * 获取历史进度数据
   */
  private static async getHistoricalProgress(managerId: number, serviceId: number, cycle: CompletionCycle) {
    const now = new Date();
    const periods = [];

    // 根据周期类型获取过去几个周期的数据
    for (let i = 1; i <= 6; i++) { // 获取过去6个周期的数据
      let startDate: Date;
      let endDate: Date;

      switch (cycle) {
        case CompletionCycle.monthly:
          startDate = new Date(now.getFullYear(), now.getMonth() - i, 1);
          endDate = new Date(now.getFullYear(), now.getMonth() - i + 1, 0);
          break;
        case CompletionCycle.quarterly:
          const currentQuarter = Math.ceil((now.getMonth() + 1) / 3);
          const targetQuarter = currentQuarter - i;
          const targetYear = targetQuarter <= 0 ? now.getFullYear() - Math.ceil(Math.abs(targetQuarter) / 4) : now.getFullYear();
          const adjustedQuarter = targetQuarter <= 0 ? 4 + (targetQuarter % 4) : targetQuarter;
          const quarterStartMonth = (adjustedQuarter - 1) * 3;
          startDate = new Date(targetYear, quarterStartMonth, 1);
          endDate = new Date(targetYear, quarterStartMonth + 3, 0);
          break;
        case CompletionCycle.yearly:
          startDate = new Date(now.getFullYear() - i, 0, 1);
          endDate = new Date(now.getFullYear() - i, 11, 31);
          break;
        default:
          continue;
      }

      const progress = await this.calculateManagerProgress(managerId, serviceId, startDate, endDate);
      if (progress.totalClients > 0) {
        periods.push({
          period: `${startDate.getFullYear()}-${startDate.getMonth() + 1}`,
          progressRate: progress.progressRate,
          completedCount: progress.completedCount,
          totalClients: progress.totalClients,
        });
      }
    }

    return periods;
  }

  /**
   * 计算横向对比数据
   */
  private static calculatePeerComparison(currentRate: number, peerRates: number[]) {
    if (peerRates.length === 0) {
      return {
        avgRate: currentRate,
        percentile: 50,
        ranking: 1,
        totalPeers: 1,
        comparison: 'no_peers' as const,
      };
    }

    const allRates = [...peerRates, currentRate].sort((a, b) => b - a);
    const avgRate = peerRates.reduce((sum, rate) => sum + rate, 0) / peerRates.length;
    const ranking = allRates.indexOf(currentRate) + 1;
    const percentile = ((allRates.length - ranking) / (allRates.length - 1)) * 100;

    let comparison: 'above_average' | 'average' | 'below_average';
    if (currentRate > avgRate + 5) {
      comparison = 'above_average';
    } else if (currentRate < avgRate - 5) {
      comparison = 'below_average';
    } else {
      comparison = 'average';
    }

    return {
      avgRate: Math.round(avgRate * 100) / 100,
      percentile: Math.round(percentile),
      ranking,
      totalPeers: allRates.length,
      comparison,
    };
  }

  /**
   * 计算历史对比数据
   */
  private static calculateHistoricalComparison(currentRate: number, historicalData: any[]) {
    if (historicalData.length === 0) {
      return {
        avgHistoricalRate: currentRate,
        lastPeriodRate: null,
        trend: 'no_history' as const,
        improvement: 0,
      };
    }

    const historicalRates = historicalData.map(d => d.progressRate);
    const avgHistoricalRate = historicalRates.reduce((sum, rate) => sum + rate, 0) / historicalRates.length;
    const lastPeriodRate = historicalRates[0]; // 最近的历史数据

    let trend: 'improving' | 'stable' | 'declining' | 'no_history';
    const improvement = currentRate - avgHistoricalRate;

    if (Math.abs(improvement) < 5) {
      trend = 'stable';
    } else if (improvement > 0) {
      trend = 'improving';
    } else {
      trend = 'declining';
    }

    return {
      avgHistoricalRate: Math.round(avgHistoricalRate * 100) / 100,
      lastPeriodRate,
      trend,
      improvement: Math.round(improvement * 100) / 100,
    };
  }

  /**
   * 计算时间进度
   */
  private static calculateTimeProgress(startDate: Date, endDate: Date): number {
    const now = new Date();
    const totalDuration = endDate.getTime() - startDate.getTime();
    const elapsed = now.getTime() - startDate.getTime();
    return Math.max(0, Math.min(1, elapsed / totalDuration));
  }

  /**
   * 综合评估进度状态
   */
  private static calculateProgressAssessment(input: {
    currentProgress: { progressRate: number };
    peerComparison: { comparison: string; percentile: number };
    historicalComparison: { trend: string; improvement: number };
    timeProgress: number;
  }) {
    const { currentProgress, peerComparison, historicalComparison, timeProgress } = input;
    const currentRate = currentProgress.progressRate;
    
    const reasons = [];
    let score = 0;

    // 基础分数（当前进度）
    score += currentRate;

    // 时间因素调整
    const expectedRate = timeProgress * 100;
    if (currentRate >= expectedRate) {
      score += 10;
      reasons.push('进度符合时间预期');
    } else {
      score -= 5;
      reasons.push('进度略低于时间预期');
    }

    // 横向对比调整
    if (peerComparison.comparison === 'above_average') {
      score += 15;
      reasons.push(`表现优于同事平均水平`);
    } else if (peerComparison.comparison === 'below_average') {
      score -= 10;
      reasons.push(`表现低于同事平均水平`);
    } else {
      reasons.push(`表现处于同事平均水平`);
    }

    // 历史对比调整
    if (historicalComparison.trend === 'improving') {
      score += 10;
      reasons.push('相比历史表现有所提升');
    } else if (historicalComparison.trend === 'declining') {
      score -= 10;
      reasons.push('相比历史表现有所下降');
    } else if (historicalComparison.trend === 'stable') {
      reasons.push('表现与历史水平持平');
    }

    // 最终状态评定
    let status: 'excellent' | 'good' | 'normal' | 'attention' | 'behind';
    
    if (score >= 95) {
      status = 'excellent';
    } else if (score >= 80) {
      status = 'good';
    } else if (score >= 60) {
      status = 'normal';
    } else if (score >= 40) {
      status = 'attention';
    } else {
      status = 'behind';
    }

    return {
      score: Math.round(score),
      status,
      reasons,
      summary: this.generateStatusSummary(status, currentRate, peerComparison, historicalComparison),
    };
  }

  /**
   * 生成状态摘要
   */
  private static generateStatusSummary(
    status: string,
    currentRate: number,
    peerComparison: any,
    historicalComparison: any
  ): string {
    const rate = Math.round(currentRate);
    
    switch (status) {
      case 'excellent':
        return `进度优秀（${rate}%），超越${peerComparison.percentile}%同事`;
      case 'good':
        return `进度良好（${rate}%），表现${peerComparison.comparison === 'above_average' ? '优于' : '符合'}预期`;
      case 'normal':
        return `进度正常（${rate}%），处于合理范围内`;
      case 'attention':
        return `需要关注（${rate}%），建议加快进度`;
      case 'behind':
        return `进度落后（${rate}%），需要重点关注`;
      default:
        return `当前进度${rate}%`;
    }
  }
}
